#include <stdio.h>
#include <config.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/time.h>
#include <input_manager.h>

static PT_inputOpr 	g_ptInputOprHead;
static T_inputEvent g_ptInputEvent;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

int registerInputOpr(PT_inputOpr ptInputOpr)
{
	PT_inputOpr temp = g_ptInputOprHead;

	if(ptInputOpr ==NULL)
	{
		fprintf(stderr,"argument error\n");
		return -1;
	}
	
	if(g_ptInputOprHead ==NULL)
	{
		g_ptInputOprHead = ptInputOpr;
	}
	else
	{
		while(temp->next !=NULL)
		{
			temp = temp->next;
		}
		temp->next = ptInputOpr;
	}

	return 0;
}

void showInputOpr(void)
{
	int i=0;
	PT_inputOpr temp = g_ptInputOprHead;

	while(temp!=NULL)
	{
		printf("%02d %s\n",i++,temp->name);
		temp = temp->next;
	}
}

int inputInit(void)
{
	int ret;
	
	ret = stdinInit();
	ret |=touchInit();

	return ret;
}

static void *start_routine(void *ptr)
{
	T_inputEvent InputEventData;
	PT_inputOpr temp = ptr;

	while(1)
	{
		if(temp->getInputEvent(&InputEventData) ==0)
		{
			pthread_mutex_lock(&mutex);
			g_ptInputEvent = InputEventData;
			
			pthread_cond_signal(&cond);
			pthread_mutex_unlock(&mutex);
		}
	}

	pthread_exit(NULL);
}

int initAllInputOpr(void)
{
	int ret;
	PT_inputOpr temp = g_ptInputOprHead;

	while(temp !=NULL)
	{
		if(temp->inputDeviceInit() ==0)
		{
			ret = pthread_create(&temp->tid,NULL,start_routine,temp);
			if(ret !=0)
			{
				fprintf(stderr,"pthread_create error %s\n",strerror(errno));
				return -1;
			}
		}
		
		temp = temp->next;
	}

	return 0;
}

int getInputEvent(PT_inputEvent ptInputEvent)
{
	pthread_mutex_lock(&mutex);
	pthread_cond_wait(&cond, &mutex);

	*ptInputEvent = g_ptInputEvent;
	pthread_mutex_unlock(&mutex);

	return 0;
}

int inputExit(void)
{
	PT_inputOpr temp = g_ptInputOprHead;

	while(temp!=NULL)
	{
		pthread_cancel(temp->tid);
		pthread_join(temp->tid,NULL);
		temp = temp->next;
	}

	pthread_mutex_unlock(&mutex);
	pthread_mutex_destroy(&mutex);
//	pthread_cond_destroy(&cond);

	while(temp!=NULL)
	{
		if(temp->inputDeviceExit)
			temp->inputDeviceExit();

		temp = temp->next;
	}

	return 0;
}

